// 在 user_model.dart 中添加 isLoading 状态
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:labcloud_app/config/token_storage.dart';
import 'package:labcloud_app/data/user.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:labcloud_app/api/graphql_config.dart';

import '../../config/constant.dart';

class UserModel extends ChangeNotifier {
  User? _user;
  bool _isLoading = false;

  User? get user => _user;
  bool get isLoggedIn => _user != null;
  bool get isLoading => _isLoading;

  UserModel()  {
    // 初始化GraphQL客户端
    _loadUserFromStorage();
  }

  // 设置用户（用于登录后设置用户信息）
  void setUser(User user) {
    _user = user;
    notifyListeners();
  }

  // 设置加载状态
  void setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  // 从持久化存储加载用户信息
  Future<void> _loadUserFromStorage() async {
    _isLoading = true;
    notifyListeners();

    final prefs = await SharedPreferences.getInstance();
    final userData = prefs.getString(Constants.USER_KEY);

    if (userData != null) {
      try {
        final userJson = jsonDecode(userData);
        var user = User.fromJson(userJson);

        // 保存token
        TokenStorage.saveTokens(user.accessToken!, user.refreshToken ?? '');
        user.refreshToken = '';
        user.accessToken = '';
        _user = user;

      } catch (e) {
        // 解析失败，清除数据
        await prefs.remove(Constants.USER_KEY);
      }
    }

    _isLoading = false;
    notifyListeners();
  }

  // 保存用户信息到持久化存储
  Future<void> saveUserToStorage() async {
    if (_user != null) {
      final prefs = await SharedPreferences.getInstance();
      final userData = jsonEncode(_user!.toJson());
      await prefs.setString(Constants.USER_KEY, userData);
    }
  }

  // 清除用户信息（退出登录）
  Future<void> clearUser() async {
    _user = null;
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(Constants.USER_KEY);
    notifyListeners();
  }
}
